package com.xhs.service;

import com.xhs.dto.BrowserSession;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Playwright会话清理服务
 *
 * @author xhs
 */
@Slf4j
@Service
public class PlaywrightCleanupService {

    @Autowired
    private PlaywrightService playwrightService;

    /**
     * 每分钟执行一次，检查并关闭超过5分钟的会话
     */
    @Scheduled(fixedRate = 60000) // 每60秒执行一次
    public void cleanupExpiredSessions() {
        log.debug("开始检查过期的Playwright会话...");
        
        try {
            // 获取所有活跃会话
            Map<String, BrowserSession> activeSessions = playwrightService.getActiveSessions();
            
            if (activeSessions.isEmpty()) {
                log.debug("没有活跃的Playwright会话");
                return;
            }
            
            LocalDateTime now = LocalDateTime.now();
            List<String> expiredSessionIds = new ArrayList<>();
            
            // 检查每个会话是否超过5分钟
            for (Map.Entry<String, BrowserSession> entry : activeSessions.entrySet()) {
                String sessionId = entry.getKey();
                BrowserSession session = entry.getValue();
                
                if (session.getCreateTime().plusMinutes(5).isBefore(now)) {
                    expiredSessionIds.add(sessionId);
                    log.info("发现过期会话: sessionId={}, phoneNumber={}, createTime={}", 
                            sessionId, session.getPhoneNumber(), session.getCreateTime());
                }
            }
            
            // 关闭过期的会话
            for (String sessionId : expiredSessionIds) {
                try {
                    playwrightService.closeSession(sessionId);
                    log.info("已关闭过期会话: sessionId={}", sessionId);
                } catch (Exception e) {
                    log.error("关闭过期会话失败: sessionId={}", sessionId, e);
                }
            }
            
            if (expiredSessionIds.isEmpty()) {
                log.debug("没有过期的Playwright会话");
            } else {
                log.info("清理完成，共关闭{}个过期会话", expiredSessionIds.size());
            }
            
        } catch (Exception e) {
            log.error("清理过期会话失败", e);
        }
    }
} 